package com.bitejiuyeke.forum.Controller;


import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.model.User;
import com.bitejiuyeke.forum.services.IUserService;
import com.bitejiuyeke.forum.utils.MD5Utils;
import com.bitejiuyeke.forum.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

//这是一个返回数据的Controller
@RestController
@Slf4j
@RequestMapping("/user")
@Api(tags = "用户")
public class UserController {


    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        //校验密码是否相同
        if (!password.equals(passwordRepeat)) {

            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        String salt = UUIDUtils.UUID_32();
        String entryPassword = MD5Utils.md5Salt(password, salt);
        user.setPassword(entryPassword);
        user.setSalt(salt);

        userService.CreateUser(user);
        //返回
        return AppResult.success();
    }




}
